/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ChatDialog.java
 *

 */
package chatclient;

import java.awt.event.WindowEvent;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Vector;
import javax.swing.SwingUtilities;

class ChatThread extends Thread {

    public ChatDialog dlg;
    public boolean done = false;
    public Vector<String> roomNames;
    public Vector<String> roomNamesPrivate;
    public Vector<String> chatterNames;
    public ArrayList<ChatRoom> lstRoomNames;

    public ChatThread(ChatDialog dlg) {
        super();
        this.dlg = dlg;
        this.roomNames = dlg.roomNames;
        this.chatterNames = dlg.chatterNames;
        this.roomNamesPrivate = dlg.roomNamesPrivate;
        //chua xu ly
        lstRoomNames = new ArrayList<ChatRoom>();
    }

    private ChatRoom GetChatRoom(String str) {
        if (str.equals("")) {
            return null;
        }
        ChatRoom result = null;
        String[] res = str.split(",");
        if (res.length == 3) {
            result = new ChatRoom();
            if (res[0] != null && res[1] != null && res[2] != null) {
                result.setName(res[0].toString());
                if (res[1].equals("true")) {
                    result.setIsPrivate(true);
                } else {
                    result.setIsPrivate(false);
                }
                result.setPassword(res[2]);
            }
        }
        return result;
    }

    @Override
    public void run() {
        Scanner in = dlg.in;
        int count = 0;
        ChatRoom temp;
        while (!done) {
            try {
                if (dlg.clientSocket.getInputStream().available() > 0) {
                    String command = in.nextLine();
                    if (command.equals("LISTROOM")) {
                        lstRoomNames.clear();
                        roomNamesPrivate.clear();
                        roomNames.clear();

                        String line;
                        while (!(line = in.nextLine()).equals("END")) {
                            if (!line.equals("START")) {
                                temp = GetChatRoom(line);
                                if (temp != null) {
                                    lstRoomNames.add(temp);
                                    if (temp.getIsPrivate()) {
                                        roomNamesPrivate.add(temp.getName());
                                    } else {
                                        roomNames.add(temp.getName());
                                    }
                                }
                            }
                        }
                        Runnable runnable = new Runnable() {
                            public void run() {
                                dlg.lstRooms.setListData(roomNames);
                                dlg.lstPrivateRoom.setListData(roomNamesPrivate);
                            }
                        };
                        SwingUtilities.invokeAndWait(runnable);
                    } else if (command.equals("JOINROOM")) {
                        chatterNames.clear();
                        String line;
                        while (!(line = in.nextLine()).equals("END")) {
                            if (!line.equals("START")) {
                                chatterNames.add(line);
                            }
                        }
                        Runnable runnable = new Runnable() {
                            public void run() {
                                dlg.lstChatters.setListData(chatterNames);
                            }
                        };
                        SwingUtilities.invokeAndWait(runnable);
                        dlg.getRoomList();
                    } else if (command.equals("NEWCHATTER")) {
                        System.out.println("Have NewCHATTER");
                        chatterNames.add(in.nextLine());
                        Runnable runnable = new Runnable() {
                            public void run() {
                                dlg.lstChatters.setListData(chatterNames);
                            }
                        };
                        SwingUtilities.invokeAndWait(runnable);
                        dlg.getRoomList();

                    } else if (command.equals("CHATTERLEAVE")) {
                        String chatterName = in.nextLine();
                        for (int i = 0; i < chatterNames.size(); i++) {
                            if (chatterNames.get(i).equals(chatterName)) {
                                chatterNames.remove(i);
                                break;
                            }
                        }
                        Runnable runnable = new Runnable() {
                            public void run() {
                                dlg.lstChatters.setListData(chatterNames);
                            }
                        };
                        SwingUtilities.invokeAndWait(runnable);
                        dlg.getRoomList();
                    } else if (command.equals("CHAT")) {
                        final String data = in.nextLine();
                        Runnable runnable = new Runnable() {
                            public void run() {
                                dlg.txtRoomText.setText(dlg.txtRoomText.getText() + "\n" + data);
                            }
                        };
                        SwingUtilities.invokeAndWait(runnable);

                    } else if (command.equals("EXIT")) {
                        done = true;
                        break;
                    }
                }

                Thread.sleep(10);
                count = (count + 1) % 1000;
                if (count == 0) {
                    dlg.getRoomList();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 *
 * @author Administrator
 */
public class ChatDialog extends javax.swing.JDialog {

    public Socket clientSocket = null;
    public PrintWriter out = null;
    public Scanner in = null;
    public Vector<String> roomNames = new Vector<String>();
    public Vector<String> chatterNames = new Vector<String>();
    public Vector<String> roomNamesPrivate = new Vector<String>();
    public ChatThread chatThread = new ChatThread(this);

    public void init(Socket clientSocket, PrintWriter out, Scanner in) {
        this.clientSocket = clientSocket;
        this.out = out;
        this.in = in;
        chatThread.start();
        getRoomList();
    }

    public void getRoomList() {
        out.println("LISTROOM");
        out.flush();
    }

    @Override
    protected void processWindowEvent(WindowEvent e) {
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            // Your code here.
            out.println("EXIT");
            out.flush();
            try {
                chatThread.join();
            } catch (Exception ex) {
            }
            System.exit(0);
        }
    }

    /**
     * Creates new form ChatDialog
     */
    public ChatDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        this.setTitle("Chat Dialog");
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblRoom = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtRoomText = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        lstChatters = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        btnJoin = new javax.swing.JButton();
        txtChat = new javax.swing.JTextField();
        btnSend = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        jTabRoom = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstRooms = new javax.swing.JList();
        jScrollPane4 = new javax.swing.JScrollPane();
        lstPrivateRoom = new javax.swing.JList();
        jpfPassword = new javax.swing.JPasswordField();
        jlbState = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jlbError = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setBackground(new java.awt.Color(204, 204, 255));
        setPreferredSize(new java.awt.Dimension(810, 500));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        lblRoom.setText("Rooms:");
        getContentPane().add(lblRoom, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, -1, -1));

        txtRoomText.setColumns(20);
        txtRoomText.setRows(5);
        jScrollPane2.setViewportView(txtRoomText);

        getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 50, 398, 350));

        jScrollPane3.setViewportView(lstChatters);

        getContentPane().add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 50, 170, 350));

        jLabel1.setText("Chatters:");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(64, 11, -1, -1));

        btnJoin.setText("Join");
        btnJoin.setPreferredSize(new java.awt.Dimension(50, 50));
        btnJoin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnJoinActionPerformed(evt);
            }
        });
        getContentPane().add(btnJoin, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 410, 170, 50));
        getContentPane().add(txtChat, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 410, 400, 50));

        btnSend.setText("Send");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });
        getContentPane().add(btnSend, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 410, 80, 50));

        btnClose.setText("Close");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });
        getContentPane().add(btnClose, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 410, 70, 50));

        jTabRoom.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jTabRoomStateChanged(evt);
            }
        });

        jScrollPane1.setViewportView(lstRooms);

        jTabRoom.addTab("General", jScrollPane1);

        jScrollPane4.setViewportView(lstPrivateRoom);

        jTabRoom.addTab("Private", jScrollPane4);

        getContentPane().add(jTabRoom, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 31, 180, 330));
        getContentPane().add(jpfPassword, new org.netbeans.lib.awtextra.AbsoluteConstraints(61, 370, 120, 30));

        jlbState.setText("State");
        getContentPane().add(jlbState, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 380, -1, -1));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(0, 0, 102));
        jLabel2.setText("User In Room");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 30, -1, -1));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(51, 0, 51));
        jLabel3.setText("CHAT ROOM V1");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 10, -1, -1));

        jlbError.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jlbError.setForeground(new java.awt.Color(255, 0, 51));
        getContentPane().add(jlbError, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 470, -1, -1));

        setSize(new java.awt.Dimension(848, 539));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btnJoinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnJoinActionPerformed
        // TODO add your handling code here:
        this.txtRoomText.setText("");
        Boolean error = true;
        if (this.lstRooms.getSelectedIndex() > -1) {
            error = false;
            jlbError.setText("");
            out.println("JOINROOM:" + roomNames.get(this.lstRooms.getSelectedIndex()));
            out.flush();
        }
        if (this.lstPrivateRoom.getSelectedIndex() > -1) {
            error = false;
            int index = roomNames.size() + lstPrivateRoom.getSelectedIndex();
           
            if (chatThread.lstRoomNames.get(index).getPassword().equals("***")) {
                if (jpfPassword.getText() == null || jpfPassword.getText().equals("")) {
                    jlbError.setText("Can't not blank password, Please Fill Password !!!");
                } else {
                    
                    jlbError.setText("");
                    //out.println("JOINROOM:" + roomNames.get(this.lstRooms.getSelectedIndex()));
                    out.println("JOINROOM:" + chatThread.lstRoomNames.get(index).toString()+","+jpfPassword.getText().trim());
                    System.out.println("sdff");
                    out.flush();
                }
            } else {
                if (jpfPassword.getText() == null || jpfPassword.getText().equals("")) {
                    jlbError.setText("Can't not blank password, Please Fill Password !!!");
                    return;
                }
                if (jpfPassword.getText().equals(chatThread.lstRoomNames.get(index).getPassword())) {
                  
                    jlbError.setText("");
                    //out.println("JOINROOM:" + roomNamesPrivate.get(this.lstPrivateRoom.getSelectedIndex()));
                    out.println("JOINROOM:" + chatThread.lstRoomNames.get(index).getName());
                    out.flush();
                } else {
                    jlbError.setText("Password Wrong, Please Try Again !!!!");
                    return;
                }
            }
        }
        if ((this.lstRooms.getSelectedIndex() < 0 || this.lstPrivateRoom.getSelectedIndex() < 0) && error) {
            jlbError.setText("Please select a room!!!!");
        }
    }//GEN-LAST:event_btnJoinActionPerformed

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        // TODO add your handling code here:

        out.println("CHAT:" + this.txtChat.getText());
        out.flush();
        this.txtChat.setText("");
    }//GEN-LAST:event_btnSendActionPerformed

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        // TODO add your handling code here:
        out.println("EXIT");
        out.flush();
        try {
            chatThread.join();
        } catch (Exception ex) {
        }
        System.exit(0);

    }//GEN-LAST:event_btnCloseActionPerformed

    private void jTabRoomStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabRoomStateChanged
        // TODO add your handling code here:
        int selectIndex = jTabRoom.getSelectedIndex();
        jlbError.setText("");
        if (selectIndex == 1) {
            jlbState.setText("Fill PW :");
            jpfPassword.setEnabled(true);
        } else {
            jlbState.setText("Not uses");
            jpfPassword.setEnabled(false);
        }
    }//GEN-LAST:event_jTabRoomStateChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("windows".equalsIgnoreCase(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ChatDialog dialog = new ChatDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnJoin;
    private javax.swing.JButton btnSend;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabRoom;
    private javax.swing.JLabel jlbError;
    private javax.swing.JLabel jlbState;
    private javax.swing.JPasswordField jpfPassword;
    private javax.swing.JLabel lblRoom;
    public javax.swing.JList lstChatters;
    public javax.swing.JList lstPrivateRoom;
    public javax.swing.JList lstRooms;
    private javax.swing.JTextField txtChat;
    public javax.swing.JTextArea txtRoomText;
    // End of variables declaration//GEN-END:variables
}
